﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using System.Windows.Threading;
using System.Threading;

namespace a12_STA_calcPrime
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool goOn = false;
        private bool notPrime = false;
        private long curPrime = 3;

        private int uiThreadId;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void StartOrStopCalc(object sender, RoutedEventArgs e)
        {
            uiThreadId = Thread.CurrentThread.ManagedThreadId;
            
            if (goOn)
            {
                goOn = false;
                startOrStopBtn.Content = "Resume";
            }
            else
            {
                goOn = true;
                startOrStopBtn.Content = "Stop";

                Debug.WriteLine(startOrStopBtn.Dispatcher);
                startOrStopBtn.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(CheckNextPrime));
            }
        }


        private void CheckNextPrime()
        {

            ProcessThreadCollection  tc = Process.GetCurrentProcess().Threads;
            int maxThread = 0;
            int completionThread = 0;
            ThreadPool.GetMaxThreads(out maxThread, out completionThread);

            Debug.WriteLine(string.Format("threadCount: {0}, maxThread: {1}, uiThread: {2}, calcThread:{3}"
                    , tc.Count
                    , completionThread
                    , uiThreadId
                    , Thread.CurrentThread.ManagedThreadId));

            var x = new Stopwatch();
            x.Start();

            notPrime = false;

            for (long i = 3; i <= Math.Sqrt(curPrime); i++)
            {
                if (curPrime % i == 0)
                {
                    // Set not a prime flag to true.
                    notPrime = true;
                    break;
                }
            }

            // If a prime number.
            if (!notPrime)
            {
                x.Stop();
                bigPrime.Text = "Bigges prime: " + curPrime.ToString();
                elapsedTime.Text = "Elapsed time: " + x.ElapsedMilliseconds.ToString();
            }

            curPrime += 2;

            if (goOn)
            {
                startOrStopBtn.Dispatcher.BeginInvoke(
                    DispatcherPriority.SystemIdle,
                    new Action(CheckNextPrime));
            }
        }
    }
}
